import React from 'react';
import { connect } from 'dva';
import { createForm } from 'rc-form';
import cx from 'classnames';
import { WingBlank, WhiteSpace, DatePicker, Picker, InputItem, Flex, List, Button, Toast } from 'antd-mobile';
import { Link, routerRedux } from 'dva/router';
import styles from '../scale/styles.less';
import {SCALE_CHD_C, SCALE_CHD } from 'const';

function ScaleChdTemplate({ dispatch, location, form, scalevalue, detail, ...rest }) {

  const { state, query } = location;
  const { type, patientid, step, patientvalue, gender} = location.state;

  const { getFieldProps, getFieldValue, setFieldsValue, validateFields, getFieldError } = form;

  const isNativeApp = location.pathname.indexOf('/scale_chd') !== -1 && query.s === 'app';

  if (!Object.keys(scalevalue).length) {
    scalevalue = [[], []];
    dispatch({ type: 'scale/save', payload: { scalevalue } });
  }

  let infos = scalevalue[0] || []; //用户信息
  let scores = scalevalue[1] || []; //症状
  let nextStep = step + 1;
  const category = step - 2;
  const totalStep = isNativeApp ? 3 : 2;
  
  let questions;
   if (gender == 1) {
    questions = SCALE_CHD_C;
  }else{
    questions = SCALE_CHD;
  } 

  let title = '';
  if (step === 1) {
    title = '完善用户信息';
  }

  let stepQuestions = [];
  if (category >= 0 && category < 2) {
    if(!isNativeApp){
      stepQuestions = questions[0].subject;
      title = questions[category].title;
    }else{
      stepQuestions = questions[category].subject;
      title = questions[category].title;
    } 
    
  }
 const nationData = [{ label: '汉族', value: '汉族' }, { label: '其他', value: '其他' },];
 const birthHistoryData = [{ label: '足月', value: '足月' }, { label: '早产', value: '早产' }];
 const birthCaesareanData = [{ label: '是', value: '剖腹产' }, { label: '否', value: '' }];
 const birthSickData = [{ label: '无', value: '无' }, { label: '有', value: '有' }];
 const parentSickData = [{ label: '哮喘病史', value: 'parentSick_1' }, { label: '过敏性疾病', value: 'parentSick_2' }, { label: '易感冒史', value: 'parentSick_3' }, { label: '无上述病史', value: 'parentSick_0' }];
 const dataSickData = [{ label: '1周以内', value: 1 }, { label: '1-2周', value: 2 }, { label: '2周以上', value: 3 }];
  const validateForm = () => {

    validateFields((err, values) => {
      if (err) {
        const fieldNames = Object.keys(err);
        if (fieldNames[0]) {
          return Toast.fail(getFieldError(fieldNames[0]));
        }
      } else {
        if (step === 1) {
          const parentSick = infos[6] || [];
          Object.keys(values).forEach((key) => {
            if (values[key] && key.indexOf('parentSick_') >= 0) {
              parentSick.push(values[key]);
            }
          });

          const nation = getFieldValue('nation');
          const height = getFieldValue('height');
          const weight = getFieldValue('weight');
          const birthHistory = getFieldValue('birthHistory');
          const birthWeight = getFieldValue('birthWeight');
          const birthSick = getFieldValue('birthSick');
          const birthCaesarean = getFieldValue('birthCaesarean');
          const dataSick = getFieldValue('dataSick')

          infos = [nation, weight, height, birthHistory, birthWeight, birthSick, parentSick, birthCaesarean, dataSick];
        }

        if (step > 1) {
          scores.push(`100:${infos[8]}`)
          Object.keys(values).forEach((key) => {
            if (values[key]) {
              scores.push(`${key}:${values[key]}`);
            }
          });
        }
        let obj={};
        for (var i = scores.length - 1; i >= 0; i--) {
          obj[scores[i].substr(0,scores[i].indexOf(":"))]=scores[i].substr(scores[i].indexOf(":")+1,scores[i].length);
        }
        scores=[];
        for(let i in obj){
          scores.push(i+":"+obj[i]);
        }
        dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });

        if (nextStep <= 2) {
          // '下一页'
          let pathname = location.pathname;
          if (isNativeApp) {
            pathname = `${location.pathname}?s=${query.s}&doctorid=${query.doctorid}&memberid=${query.memberid}`;
          }
          dispatch(
            routerRedux.replace({
              pathname,
              state: {
                type,
                patientid,
                step: nextStep,
                gender: state.gender
              },
            }),
          );
        } else {
          // 最后一页'提交'
          infos[3] += infos[7];
          if(infos[5] == "无"){
            scores.splice(0,1);
          }
          const patientValue = `${infos[4]}|${infos[1]}|${infos[2]}|${infos[3]}|${infos[5]}|${infos[6].join(';')}|${scores.join(';')}`;
          Toast.loading('正在加载');
          dispatch({
            type: 'scale/submitQuestions',
            payload: {
              // type: query.type || state.type,
              type: 'chd',
              patientId: state.patientid,
              familyId:  JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId,
              patientValue,
              ...rest,
            },
          });
        }
      }
    });
  };

  function handleChange({ target: { type, name, value } }) {

    if (Array.from(scores).find(item => item.split(':')[0] === name && item.split(':')[1] === value)) {
      setFieldsValue({ [name]: value }); //form实际值与状态不符，用赋值保持相符
      scores = Array.from(scores).filter(item => item !== `${name}:${value}`); //从scores中去除
    }
    
    if (infos[6] && Array.from(infos[6]).find(item => item === value)) {
      setFieldsValue({ [name]: value }); //form实际值与状态不符，用赋值保持相符 
      infos[6] = Array.from(infos[6]).filter(item => item !== value); //从scores中去除
    }
    if(name == "parentSick_0"){
      setFieldsValue({ ["parentSick_1"]: null });
      setFieldsValue({ ["parentSick_2"]: null });
      setFieldsValue({ ["parentSick_3"]: null });
      infos[6] = [];
    }
    if(name == "parentSick_1" || name == "parentSick_2" || name == "parentSick_3"){
      setFieldsValue({ ["parentSick_0"]: null });
    }

    if (getFieldValue(name) === value) {
      setFieldsValue({ [name]: null });
    } else {
      setFieldsValue({ [name]: value });
    }
    
    if(name == 122 ){
      setFieldsValue({ [123]: null });
    }
    if(name == 123 ){
      setFieldsValue({ [122]: null });
    }

    dispatch({ type: 'scale/save', payload: { scalevalue: [infos, scores] } });
  }

  function isActive(key, value, i) {
    if(infos[6] && Array.from(infos[6]).find(item => item === value)) {
      return true;
    }
    if (Array.from(scores).find(item => item.split(':')[0] === key && item.split(':')[1] === value)) {
      if(getFieldValue(key) && getFieldValue(key)!=value){
        return false;
      }else{
        return true;
      }
      return true;
    }
    if (!getFieldValue(key)) {
      return false;
    }

    return getFieldValue(key) === value;
  }

  function nextHandler() {
    window.scrollTo(0, 0);
    nextStep = step + 1;
    validateForm();
  }

  function prevHandler() {
    window.scrollTo(0, 0);
    nextStep = step - 1;
    validateForm();
  }

  function submitHandler() {
    nextStep = step + 1;
    validateForm();
  }
  function isBlur(type,value){
     if (type == "nation"){
        if (value.length < 0 || value.length > 5) {
          setFieldsValue({[type]: null});
          return Toast.fail("请输入正确的民族0~5个汉字!", 1);
        }
    }
     if (type == "height") {
        if (value < 25 || value > 180) {
          setFieldsValue({[type]: null});
          return Toast.fail("请输入正确的身高25~180cm！", 1);
        }
    }
    if (type == "weight") {
        if (value < 1 || value > 100) {
          setFieldsValue({[type]: null});
          return Toast.fail("请输入正确的体重1~100kg！", 1);
        }
    }
    if (type == "birthWeight"){
        if (value < 1 || value > 8) {
          setFieldsValue({[type]: null});
          return Toast.fail("请输入正确的出生体重1~8kg！", 1);
        }
    }
  }

  return (
    <WingBlank size="md">
      <WhiteSpace />
      <List>
        <List.Item>
          <Flex justify="center">{`${step}/${totalStep} ${title}`}</Flex>
          {step!==1?
            <div>
               <Flex justify="center" style={{marginTop: '0.1rem'}}>请最了解孩子症状的家长进行回答</Flex>
               <Flex justify="center">依据您孩子近1年的症状加以总结</Flex>
               <Flex justify="center">（有则选，无则不选，可以多选）</Flex>
            </div>:""}
        </List.Item>
        {step === 1
          ? /*第1页自定义表单*/
            <div>
              <Picker
                data={nationData}
                {...getFieldProps('nation', {
                  initialValue: infos[0] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入民族' }],
                    },
                  ],
                })}
              >
                <List.Item arrow="horizontal">民族</List.Item>
              </Picker>
               <Picker
                data={birthHistoryData}
                {...getFieldProps('birthHistory', {
                  initialValue: infos[3] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请选择出生史' }],
                    },
                  ],
                })}
              >
                <List.Item arrow="horizontal">出生史</List.Item>
              </Picker>
               <Picker
                data={birthCaesareanData}
                {...getFieldProps('birthCaesarean', {
                  initialValue: infos[7] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请选择是否是剖妇产' }],
                    },
                  ],
                })}
              >
                <List.Item arrow="horizontal">是否是剖腹产</List.Item>
              </Picker>
                <InputItem
                {...getFieldProps('birthWeight', {
                  initialValue: infos[4] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入出生体重' }],
                    },
                  ],
                  normalize:(v, prev) => {
                    if (v && !/^(([1-9]\d*)|0)(\.\d{0,1}?)?$/.test(v)) {
                      if (v === '.') {
                        return '0.';
                      }
                      return prev;
                    }
                    return v;
                  },
                })}
                placeholder="请输入出生体重"
                type="digit" 
                onBlur={() => isBlur("birthWeight",getFieldValue('birthWeight'))}
              >
                出生体重(kg)
              </InputItem>
              <Picker
                data={birthSickData}
                {...getFieldProps('birthSick', {
                  initialValue: infos[5] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请选择新生儿疾病' }],
                    },
                  ],
                })}
              >
                <List.Item arrow="horizontal">新生儿疾病</List.Item>
              </Picker>
              { getFieldValue('birthSick') == "有"?<Picker
                data={dataSickData}
                {...getFieldProps('dataSick', {
                  initialValue: infos[8] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请选择住院日期' }],
                    },
                  ],
                })}
              >
                <List.Item arrow="horizontal">住院时间</List.Item>
              </Picker>:""}
              <List.Item key="parentSick">
                父母方面的疾病
                <List.Item.Brief>
                  <Flex wrap="wrap" className={styles.questionOptions}>
                    {parentSickData.map((option, i) => {
                      const key = option.value;
                      const value = option.label;
                      return (
                        <label key={key} className={cx(styles.questionOption, styles.questionOptionNormal, { [styles.questionOptionActive]: isActive(key, value, i) })}>
                          <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} checked={isActive(key, value, i)} onChange={handleChange} />
                          {value}
                        </label>
                      );
                    })}
                  </Flex>
                </List.Item.Brief>
              </List.Item>
            <InputItem
                {...getFieldProps('weight', {
                  initialValue: infos[1] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入体重' }],
                    },
                  ],
                  normalize:(v, prev) => {
                    if (v && !/^(([1-9]\d*)|0)(\.\d{0,1}?)?$/.test(v)) {
                      if (v === '.') {
                        return '0.';
                      }
                      return prev;
                    }
                    return v;
                  },
                })}
                placeholder="请输入体重"
                type="digit" 
                onBlur={() => isBlur("weight",getFieldValue('weight'))}
              >
                目前体重(kg)
              </InputItem>
              <InputItem
                {...getFieldProps('height', {
                  initialValue: infos[2] || '',
                  validate: [
                    {
                      trigger: false,
                      rules: [{ required: true, message: '请输入身高' }],
                    },
                  ],
                  normalize:(v, prev) => {
                    if (v && !/^(([1-9]\d*)|0)(\.\d{0,1}?)?$/.test(v)) {
                      if (v === '.') {
                        return '0.';
                      }
                      return prev;
                    }
                    return v;
                  },
                })}
                placeholder="请输入身高"
                type="digit" 
                onBlur={() => isBlur("height",getFieldValue('height'))}
              >
                目前身高(cm)
              </InputItem>
            </div>
          : /*第2,3页动态题目*/
            stepQuestions.map((question, i) => (
              <List.Item wrap multipleLine key={`s${i + 1}`} >
                {`${i + 1}. ${question.title}`}
                <List.Item.Brief>
                  {question.type === '3'
                    ? //包含子题
                      question.subject.map((question, i) => {
                        let Ans;
                        if (question.type === '2') {
                          //子题，多选题
                          Ans = (
                            <Flex wrap="wrap" className={styles.questionOptions} key={`ans_2_${i + 1}`}>

                              {question.choiceKey.split('|').map((option, i) => {
                                const key = question.code.split('|')[i];
                                let value = "1";
                                if (question.choiceValue) {
                                  value = question.choiceValue.split('|')[i]
                                }
                                return (
                                  <div key={`ans_2_div_${i}_${key}_${value}`}>
                                    <label key={`${key}_${value}`} className={cx(styles.questionOption, styles.questionOptionNormal, { [styles.questionOptionActive]: isActive(key, value, i) })}>
                                      <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} checked={isActive(key, value, i)} onChange={handleChange} />
                                      {option}
                                    </label>
                                  </div>
                                );
                              })}
                            </Flex>
                          );
                        } else {
                          //子题，单选题
                          Ans = (
                            <Flex wrap="wrap" className={styles.questionOptions} key={`ans_1_${i + 1}`}>
                              {question.choiceKey.split('|').map((option, i) => {
                                const key = question.code;
                                const value = question.choiceValue.split('|')[i];
                                return (
                                  <div key={`ans_3_div_${i}_${key}_${value}`}>
                                    <label key={`${key}_${value}`} className={cx(styles.questionOption, styles.questionOptionNormal, { [styles.questionOptionActive]: isActive(key, value, i) })}>
                                      <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} checked={isActive(key, value, i)} onChange={handleChange} />
                                      {option}
                                    </label>
                                  </div>
                                );
                              })}
                            </Flex>
                          );
                        }

                        const Sub = (
                          <div key={`div${i + 1}`}>
                            <Flex direction="row" key={`${i + 1}`}>
                              <Flex.Item key={`${i + 1}`}>
                                {question.title}
                              </Flex.Item>
                            </Flex>
                            <WhiteSpace size="xs" />
                            {Ans}
                            <WhiteSpace size="md" />
                          </div>
                        );

                        return Sub;
                      })
                    : question.type === '2'
                        ? //多选题
                          <Flex wrap="wrap" className={styles.questionOptions} key={`1_${i + 1}`}>
                            {question.choiceKey.split('|').map((option, i) => {
                              const key = question.code.split('|')[i];
                              const value = '1';
                              return (
                                <label key={`${key}_${value}`} className={cx(styles.questionOption, styles.questionOptionNormal, { [styles.questionOptionActive]: isActive(key, value, i) })}>
                                  <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} checked={isActive(key, value, i)} onChange={handleChange} />
                                  {option}
                                </label>
                              );
                            })}
                          </Flex>
                        : //单选题
                          <Flex wrap="wrap" className={styles.questionOptions} key={`2_${i + 1}`}>
                            {question.choiceKey.split('|').map((option, i) => {
                              const key = question.code;
                              const value = question.choiceValue.split('|')[i];
                              return (
                                <label key={`${key}_${value}`} className={cx(styles.questionOption, styles.questionOptionNormal, { [styles.questionOptionActive]: isActive(key, value, i) })}>
                                  <input {...getFieldProps(`${key}`)} type="checkbox" name={key} value={value} checked={isActive(key, value, i)} onChange={handleChange} />
                                  {option}
                                </label>
                              );
                            })}
                          </Flex>}
                </List.Item.Brief>
              </List.Item>
            ))}
        <div>
          <WhiteSpace size="xl" />
          <WingBlank>
            <Flex>
              {step === 1
                ? null
                : <Flex.Item>
                  <Button onClick={prevHandler}>上一页</Button>
                </Flex.Item>}

              {step < totalStep
                ? <Flex.Item>
                  <Button type="primary" onClick={nextHandler}>下一页</Button>
                </Flex.Item>
                : <Flex.Item>
                  <Button type="primary" onClick={submitHandler}>提交</Button>
                </Flex.Item>}

            </Flex>
          </WingBlank>
          <WhiteSpace size="xl" />
        </div>
      </List>
      <WhiteSpace size="xl" />
    </WingBlank>
  );
}

export default connect(({ scale }) => ({ ...scale }))(createForm()(ScaleChdTemplate));
